package cn.com.cetccst.tools.ui;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

public class ThreadSafeToast {
    private static Handler handler;
    private static Context context;
    private static Toast curToast;

    public static void initialize(Context context) {
        ThreadSafeToast.context = context;
        handler = new Handler();
    }

    public static boolean isMainThread() {
        return Looper.getMainLooper() == Looper.myLooper();
    }

    public static void show(final String message, final int duration) {
        if (isMainThread()) {
            showInMainThread(message, duration);
        } else {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    showInMainThread(message, duration);
                }
            });
        }
    }

    public static void show(final int resId, final int duration) {
        if (isMainThread()) {
            showInMainThread(resId, duration);
        } else {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    showInMainThread(resId, duration);
                }
            });
        }
    }

    private static void showInMainThread(String message, int duration) {
        if (curToast != null) {
            curToast.cancel();
        }
        curToast = Toast.makeText(context, message, duration);
        curToast.show();
    }

    private static void showInMainThread(int resId, int duration) {
        if (curToast != null) {
            curToast.cancel();
        }
        curToast = Toast.makeText(context, resId, duration);
        curToast.show();
    }
}
